<?php

App::uses('CrudController', 'Controller');

class PassportsController extends AppController {

    public $components = array('RequestHandler');

    const PAGES = 5;
    const PASSPORTS_PAGE = 8;

    public function beforeFilter() {
        $this->Auth->allow();
        parent::beforeFilter();
    }

    public function index ($comp = null) {
        $appBosch = new stdClass();
        $appBosch->init = false;
        if( isset($this->request->query['team']) ){
            $teamId = $this->request->query['team'];
            $appBosch->init = true;
            $appBosch->lineId = $this->request->query['lineId'];
            $appBosch->areaId = $this->request->query['areaId'];
            
            $this->loadModel('Area');
            $this->Area->id = $appBosch->areaId;
            $resArea = $this->Area->read();
            $area    = $resArea['Area'];
            $appBosch->moeId  = $area['moe_id'];
            
            $this->loadModel('TeamUser');
            $teamUsers = $this->TeamUser->getActiveTeamUsers($teamId);
            $appBosch->nominas = '';
            
            foreach($teamUsers as $teamUser) 
            {
                $appBosch->nominas .=  $teamUser['nomina'] . ' ';
            }
        }        
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Pasaportes'));
        $this->set('description', __('Impresión de pasaportes'));
        if ($comp != null)
            $this->Session->setFlash(__('No existe ninguno de los números de nómina proporcionados o no es de un asociado'), 'default', array('class' => 'alert alert-warning'));
    }

    public function teamsPassports() {
        $teamId = $this->request->query('team');
        $lineId = $this->request->query('lineId');
        $areaId = $this->request->query('areaId');

        $this->loadModel('TeamUser');
        $users = $this->TeamUser->getUsersNominasByTeam($teamId);
        $tam = count($users);
        $payrolls = array();
        for ($i = 0; $i < $tam; $i++) {
            $payrolls[] = $users[$i]['u']['nomina'];
        }
        $this->loadModel('Passport');
        $records = $this->getDataForPassports('0', $areaId, $lineId, $payrolls);
        $tam = count($records);
        for ($i = 0; $i < $tam; $i++) {
            $security = $this->Passport->save(array(
                'data' => json_encode($records[$i]),
                'emitter_id' => $this->Auth->user('id'),
                'ip' => $this->request->clientIp()
            ));
            $records[$i]['security'] = $security['Passport']['id'];
            $records[$i]['urlQR'] = Router::url(array('controller' => 'Passports', 'action' => 'verify', $security['Passport']['id']), true);
            $this->Passport->clear();
        }

        $uv = 0;
        $tam = count($records);
        for ($i = 0; $i < $tam; $i++) {
            if (count($records[$i]['certs']) != 0) {
                $uv++;
            }
        }

        if ($uv == 0) {
            $this->redirect(array('action' => 'index', '1'));
        }

        $limit = self::PASSPORTS_PAGE * self::PAGES;

        $this->Session->write('Passports', $records);
        $this->Session->write('offset', 1);
        $this->Session->write('left', $tam - $limit);
        $data = new stdClass();
        $data->records = array_slice($records, 0, $limit);

        $this->set('data', $data);
        $appBosch = new stdClass();
        $appBosch->left = $tam - $limit;
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Pasaportes'));
        $this->set('description', __('Impresión de pasaportes'));

        $this->view = 'passports';
    }

    public function teamsPassportsAjax() {
        $left = $this->Session->read('left');
        if( $left > 0 ) {
            $limit = self::PASSPORTS_PAGE * self::PAGES;
            $records = $this->Session->read('Passports');
            $offset = $this->Session->read('offset');
            $this->Session->write('left', $left - $limit);
            $this->Session->write('offset', $offset + 1);
            $data = new stdClass();
            $data->records = array_slice($records, $offset * $limit, $limit);
            $this->set('data', $data);
        } else {
            $this->Session->delete('Passports');
            $this->Session->delete('offset');
            $this->Session->delete('left');
        }
    }

    public function passports() {
        $this->request->allowMethod('get');

        $moeId = $this->request->query('moe');
        $areaId = $this->request->query('area');
        $lineId = $this->request->query('linea');
        $payrolls = $this->request->query('payrolls');
        $payrolls = explode(' ', $payrolls);

        $this->loadModel('Passport');
        $records = $this->getDataForPassports($moeId, $areaId, $lineId, $payrolls);
        $tam = count($records);
        for ($i = 0; $i < $tam; $i++) {
            $security = $this->Passport->save(array(
                'data' => json_encode($records[$i]),
                'emitter_id' => $this->Auth->user('id'),
                'ip' => $this->request->clientIp()
            ));
            $records[$i]['security'] = $security['Passport']['id'];
            $records[$i]['urlQR'] = Router::url(array('controller' => 'Passports', 'action' => 'verify', $security['Passport']['id']), true);
            $this->Passport->clear();
        }

        $uv = 0;
        for ($i = 0; $i < count($records); $i++) {
            if (count($records[$i]['certs']) != 0) {
                $uv++;
            }
        }

        if ($uv == 0) {
            $this->redirect(array('action' => 'index', '1'));
        }

        $data = new stdClass();
        $data->records = $records;

        $this->set('data', $data);
        $appBosch = new stdClass();
        $this->set('appBosch', $appBosch);
    }

    public function passport($moeId, $areaId, $lineId, $payroll) {
        $this->request->allowMethod('get');

        $records = $this->getDataForPassports($moeId, $areaId, $lineId, $payroll);

        $data = new stdClass();
        $data->records = $records;

        $this->set('data', $data);
        $appBosch = new stdClass();
        $this->set('appBosch', $appBosch);
    }

    private function getDataForPassports($moeId, $areaId, $lineId, $payrolls) {
        $this->loadModel('Certification');

        $temp = $this->Certification->getDataForPassport($moeId, $areaId, $lineId, $payrolls);
        $tam = count($temp);

        $records = array();
        $c = -1;
        $ui = '0';
        $li = '0';
        for ($i = 0; $i < $tam; $i++) {
            if ($ui != $temp[$i]['uid'] || $li != $temp[$i]['lid']) {
                $c++;
                $ui = $temp[$i]['uid'];
                $li = $temp[$i]['lid'];
                $records[$c] = array();
                $records[$c]['nameLine'] = implode(' - ', array($temp[$i]['mname'], $temp[$i]['aname'], $temp[$i]['lname']));
                $records[$c]['catIcon'] = $temp[$i]['icon'];
                $records[$c]['catColor'] = $temp[$i]['color'];
                $records[$c]['emi'] = $this->Auth->user('full_name');
                $records[$c]['str']['title'] = __('Pasaporte');
                $records[$c]['str']['footer'] = __('Procedimiento P 0007Q Anexo 19 Pasaporte 2a Edición');
                $records[$c]['str']['msg'] = __('El portador de este pasaporte reconoce haber/estar recibiendo entrenamiento referente pero no limitado a puntos y uso de equipo de seguridad, instrucción de trabajo y demás documentación necesaria. Y queda autorizado para trabajar únicamente en la operación y tiempo establecido en este documento bajo la responsabilidad del supervisor de Producción.');
                $records[$c]['certs'] = array();
            }
            $records[$c]['certs'][] = array(
                'numNom' => $temp[$i]['numNom'],
                'nameAsc' => $temp[$i]['nameAsc'],
                'nameWork' => $temp[$i]['nameWork'],
                'sucss' => $temp[$i]['sucss'],
                'train' => $temp[$i]['train'],
                'life' => $temp[$i]['life'],
                'end' => $temp[$i]['end']
            );
        }

        return $records;
    }

    public function control() {
        $appBosch = new stdClass();
        $this->set('appBosch', $appBosch);
        $this->set('title', __('Control de Pasaportes'));
        $this->set('description', __('P0007Q Anexo 20'));
    }

    public function passportsControl($areaId, $filterSuccess = false) {
        if ($filterSuccess == 'false') {
            $filterSuccess = false;
        } elseif ($filterSuccess = 'true') {
            $filterSuccess = true;
        }
        $this->request->onlyAllow('get');
        $this->loadModel('Certification');
        $resp = $this->Certification->getPassportsControlByArea($areaId, $filterSuccess);
        $this->set(array('records' => $resp, '_serialize' => 'records'));
        $this->viewClass = 'Json';
        $this->layout = 'ajax';
    }
}
